<template>
  <div class="tabModule">
    <el-table
      v-if="isTableVis"
      ref="table"
      v-loading="loading"
      :data="tableData"
      :border="tableBorder"
      :height="tableHeight"
      :row-style="rowStyle"
      :cell-style="cellStyle"
      :tree-props="treeProps"
      :highlight-current-row="highlight"
      style="width: 100%"
      :row-class-name="tableRowClassName"
      :header-cell-style="headerCellStyle"
      :row-key="getRowKeys"
      :expand-row-keys="expandRowKeys"
      :span-method="spanMethod"
      :show-summary="showSummary"
      :summary-method="getSummaries"
      :default-expand-all="defaultExpandAll"
      :lazy="lazy"
      :load="load"
      @select="handleSelect"
      @select-all="handleSelectAll"
      @row-dblclick="openDetails"
      @row-click="openDetail"
      @header-click="headerClick"
      @cell-click="cellClick"
      @expand-change="expandChange"
      @row-contextmenu="rightClick"
    >
      <!-- 隔行变色   :row-class-name="tabRowClassName"-->
      <!--    全选-->
      <el-table-column
        v-if="tableSelection"
        align="center"
        type="selection"
        width="40"
        :reserve-selection="reserveSelection"
        :selectable="selectable"
      />
      <!--   type="selection" 为 true 则会在数据更新之后保留之前选中的数据  :reserve-selection="true"    -->
      <!--    id列 序号-->
      <el-table-column v-if="serial" type="index" :label="$t('shop.numIndex')" width="40px" align="center" />
      <el-table-column v-if="serials" type="index" fixed="left" :label="$t('shop.numIndex')" width="40px" align="center" />
      <el-table-column v-if="expand" type="expand" width="30px">
        <template slot-scope="scope">
          <slot name="expand" :scope="scope.row" />
        </template>
      </el-table-column>
      <slot />
      <el-table-column
        v-for="(col, index) of cpTableHeader"
        :key="index"
        :fixed="col.fixed"
        :prop="col.prop"
        :label="col.label"
        :width="col.width"
        :align="col.align || colAlign"
        :header-align="col.headerAlign || 'center'"
        :min-width="col.minWidth || colMinWidth"
        :show-overflow-tooltip="!col.tooltip"
        :sortable="col.sortable || sortable"
        :filters="col.filters"
        :filter-method="filterHeader"
        style="background: #1e9fff!important;"
      >
        <!-- 生产订单汇总列表 计划完工时间 批量修改按钮 -->
        <template v-if="col.prop === 'fplanfinishDate' && col.type === 'bill'" slot="header">
          <slot name="header" />
        </template>
        <!--  表格必填项显示红星*  -->
        <template v-if="col.requireg === 'must'" slot="header">
          <span style="color: #f55757">*</span>{{ col.label }}
        </template>
        <!--      操作-->
        <template slot-scope="scope">
          <!--    text      -->
          <span v-if="col.type === 'text' || !col.type">
            {{ scope.row[col.prop] }}
          </span>
          <!--        作用域插槽-->
          <!--        state-->
          <slot v-else-if="col.type === 'state'" name="btnState" :scope="scope" />
          <!--        states-->
          <slot v-else-if="col.type === 'states'" name="btnStates" :scope="scope" />
          <!--        button-->
          <slot v-else-if="col.type === 'btn'" name="btnSlot" :scope="scope" />
          <!--        tag-->
          <slot v-else-if="col.type === 'tag'" name="tagSlot" :scope="scope" />
          <!--        tag-->
          <slot v-else-if="col.type === 'bill'" name="billSlot" :scope="scope" />
          <!--        order-->
          <slot v-else-if="col.type === 'order'" name="orderSlot" :scope="scope" />
          <!--        operate-->
          <slot v-else-if="col.type === 'operate'" name="operaSlot" :scope="scope" />
          <!--        text-->
          <slot v-else-if="col.type === 'text2'" name="text2Slot" :scope="scope" />
          <!--        text-->
          <slot v-else-if="col.type === 'text1'" name="text1Slot" :scope="scope" />
          <!--        text-->
          <slot v-else-if="col.type === 'text3'" name="text3Slot" :scope="scope" />
          <!--        text-->
          <slot v-else-if="col.type === 'text4'" name="text4Slot" :scope="scope" />
          <!--        text-->
          <slot v-else-if="col.type === 'text5'" name="text5Slot" :scope="scope" />
          <!--        text-->
          <slot v-else-if="col.type === 'text6'" name="text6Slot" :scope="scope" />
        </template>
      </el-table-column>
    </el-table>
    <!-- 右键菜单 -->
    <div id="menu" class="menuDiv">
      <ul class="menuUl">
        <li @click.stop="infoClick">
          {{ $t('btn.copy') }}
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import { Message } from 'element-ui'
export default {
  name: 'Table',
  props: {
    loading: {
      type: Boolean,
      default: false
    },
    tableData: { // 表格显示的数据
      type: Array,
      required: true
    },
    tableHeader: { // 表格头部数据cellClick
      type: Array,
      required: true
    },
    tableHeight: { // 表格高度
      type: [String, Number],
      default: window.innerWidth > 1440 ? 'calc(100vh - 230px)' : '70vh'
      // default: 'auto'
    },
    tableBorder: { // 表格边框
      type: Boolean,
      default: true
    },
    tableSelection: { // 表格多选
      type: Boolean,
      default: false
    },
    showSummary: { // 开启合计行
      type: Boolean,
      default: false
    },
    reserveSelection: { // 开启合计行
      type: Boolean,
      default: false
    },
    selectable: { // 多选框是否可选
      type: Function,
      default: function() {
        return function() {}
      }
    },
    expandRowKeys: {
      type: Array,
      default: function() {
        return []
      }
    },
    spanMethod: { // 合并行列
      type: [Array, Function],
      default: function() {
        return function() {} || []
      }
    },
    load: { // 加载子节点数据的函数
      type: Function,
      default: function() {
        return function() {}
      }
    },
    getSummaries: { // 定义自己的合计逻辑
      type: [Array, Function],
      default: function() {
        return function(param) {
          console.log(param)
        } || []
      }
    },
    defaultExpandAll: {
      type: Boolean,
      default: false
    },
    tooltip: { // 单元格内容过长显示省略号
      type: Boolean,
      default: true
    },
    sortable: { // 单元格是否排序
      type: Boolean,
      default: false
    },
    colMinWidth: { // 单元格最小宽度
      type: String,
      default: '80'
    },
    serial: { // 是否显示序列号
      type: Boolean,
      default: false
    },
    expand: { // 是否显示展开行
      type: Boolean,
      default: false
    },
    serials: {
      type: Boolean,
      default: false
    },
    colAlign: { // 单元格对齐方式
      type: String,
      default: 'center'
    },
    commodity: { // 是否显示商品图片
      type: Boolean,
      default: false
    },
    highlight: { // 是否高亮當前行
      type: Boolean,
      default: function() {
        return false
      }
    },
    treeProps: {
      type: Object,
      default: function() {
        return {}
      }
    },
    cellStyle: { // 单元格style
      type: [Object, Function],
      default: function() {
        return { padding: '1px 3px' } || function(param) {
          console.log(param)
        }
      }
    },
    headerCellStyle: { // 表头style
      type: [Object, Function],
      default: function() {
        return { fontSize: '12px', padding: '5px 0' } || function(param) {
          console.log(param)
        }
      }
    },
    getRowKeys: {
      type: [Number, String],
      default: 0 || '0'
    },
    lazy: {
      type: Boolean,
      default: function() {
        return false
      }
    }
  },
  data() {
    return {
      menus: [
        { name: '复制', operType: 1 }
      ],
      scrollLeft: 0,
      scrollTop: 0,
      isTableVis: true,
      cpTableHeader: [],
      selectedIndex: [],
      cpTableData: [],
      filtrate: [] // 筛选数据
    }
  },
  watch: {
    tableData: {
      handler(val) {
        this.selectedIndex = []
        this.cpTableHeader = this.tableHeader
        this.cpTableHeader.map((res) => {
          res.filters = []
          val.forEach(item => {
            if (item[res.prop]) {
              res.filters.push({
                text: item[res.prop],
                value: item[res.prop]
              })
            }
          })
          const obj = {}
          const result = []
          res.filters.map(item => {
            if (!obj[item.text]) {
              result.push(item)
              obj[item.text] = true
            }
          })
          res.filters = result
        })
        this.$nextTick(() => {
          this.$refs.table.doLayout()
          // 表格翻页滚动到表头
          // this.$refs.table.bodyWrapper.scrollTop = 100
        })
      },
      immediate: true
      // deep: true
    }
  },
  // deactivated() {
  //   // 页面每次离开时 获取不到表格滚动距离 使用监听addEventListener
  //   // this.scrollLeft = this.$refs.table.$refs.bodyWrapper.scrollTop
  // },
  activated() {
    // 页面每次激活时 都会获取之前的scrollTop
    this.$refs.table.bodyWrapper.scrollTop = this.scrollTop
    this.$refs.table.bodyWrapper.scrollLeft = this.scrollLeft
  },
  mounted() {
    // 页面切换表格滚动位置不变
    this.dom = this.$refs.table.bodyWrapper
    this.dom.addEventListener('scroll', () => {
      // 滚动距离
      this.scrollTop = this.dom.scrollTop
      this.scrollLeft = this.dom.scrollLeft
      console.log()
    })
  },
  methods: {
    // 点击右键
    rightClick(row, column, event) {
      // 当前单元格数据
      this.copyVal = row[column.property]
      const menu = document.querySelector('#menu')
      // 阻止元素发生默认的行为
      event.preventDefault()
      // 根据事件对象中鼠标点击的位置，进行定位
      menu.style.left = event.clientX - 200 + 'px'
      menu.style.top = event.clientY - 170 + 'px'
      // 改变自定义菜单的隐藏与显示
      menu.style.display = 'block'
      menu.style.zIndex = 1000
    },
    // 自定义菜单的点击事件 右键复制
    infoClick() {
      this.$copyText(this.copyVal).then(
        function() {
          Message({
            message: '复制成功',
            type: 'success',
            showClose: true,
            duration: 500
          })
        },
        function() {
          Message({
            message: '复制失败',
            type: 'error',
            showClose: true,
            duration: 500
          })
        }
      )
      const menu = document.querySelector('#menu')
      menu.style.display = 'none'
    },
    reload() {
      this.isTableVis = false
      this.$nextTick(function() {
        this.isTableVis = true
      })
    },
    // 某些行变色
    rowStyle({ row, rowIndex }) {
      if (row.color === 2 || Number(row.fstdQty) > Number(row.stockNum)) {
        return { background: '#ECE864' } // 红 白 黄 存货收发存明细表
      } else if (row.color === 1) {
        return { background: '#FFF' } // 白
      } else if (row.color === 3 || row.forder === 1) {
        return { background: 'rgba(250,109,109,0.3)' } // 红
      } else if (row.fpushqty !== row.freqqty) { // 采购申请单列表 已下推 != 申请
        return { background: '#dbffdb' }
      } else if (row.fstate === 1 && row.fcountqty > 0) { // 盘点
        return { background: '#dbffdb' }
      } else if (this.selectedIndex.includes(rowIndex)) {
        return { background: '#fff4df' }
      } else if (row.below === 1 || row.单据类型 === '期初' || row.账套类型 === '期初') {
        return { background: '#b4fca4' }
      } else if (row.单据类型 === '期末' || row.账套类型 === '期末' || row.actualqty > 0) {
        // 期初 期末 actualqty XSDD 材料明细
        return { background: '#fde883' }
      } else {
        return { background: '#FFF' }
      }
      // else if (row.fforbidStatus === 'B') { // 禁用状态
      //     return { color: '#F39191' } // 红
      //   }
    },
    // 双击行事件
    openDetails(row) {
      this.$emit('clickRow', row)
    },
    // 单击行事件
    openDetail(row, column, event) {
      // 右键菜单
      const menu = document.querySelector('#menu')
      menu.style.display = 'none'
      // // 清除选中行
      // this.$refs.table.clearSelection()
      // 切换某一行的选中状态
      this.$refs.table.toggleRowSelection(row)
      this.handleGetSelection()
      this.$emit('rowClick', row, column, event)
    },
    // 点击表头
    headerClick(column) {
      this.$emit('headerClick', column)
    },
    // 点击单元格
    cellClick(row, column, cell, event) {
      this.$emit('cellClick', row, column, cell, event)
    },
    // 当用户对某一行展开或者关闭的时候会触发该事件
    expandChange(row) {
      this.$emit('expandChange', row)
    },
    // 勾选数据
    toggleRowSelection(row, selected) {
      this.$refs.table.toggleRowSelection(row, selected)
    },
    // 清空用户多选
    clearSelect() {
      this.$refs.table.clearSelection()
    },
    // 勾选一个
    handleSelect() {
      this.handleGetSelection()
    },
    // 全选
    handleSelectAll(selection) {
      // 用于多选表格，清空用户的选择filtrate
      this.$refs.table.clearSelection()
      if (selection.length > 0 && selection[0]) {
        selection.map(item => {
          this.$refs.table.toggleRowSelection(item)
        })
      }
      this.handleGetSelection()
    },
    // 获取勾选的值
    handleGetSelection() {
      this.selectedIndex = []
      this.$refs.table.selection.forEach(res => {
        // 选中行变色
        this.selectedIndex.push(res.index)
      })
      this.$emit('selectionChange', this.$refs.table.selection)
    },
    // 隔行变色
    // tabRowClassName({ row, rowIndex }) {
    //   const index = rowIndex + 1
    //   if (index % 2 === 0) {
    //     return 'warning-row'
    //   }
    // },
    // 筛选
    filterHeader(value, row, column) {
      this.filtrate = []
      const property = column['property']
      if (row[property] === value) {
        return this.filtrate.push(row)
      }
      return row[property] === value
    },
    tableRowClassName({ row, rowIndex }) {
      row.index = rowIndex
    }
  }
}
</script>

<style lang="scss">
.table::v-deep .success-row {
  background-color: rgb(255, 244, 232);
  //background-color: rgb(85, 55, 218);
}
//0.68vw = 13px
.el-table__column-filter-trigger {
  display: none;
}
th:hover {
  .el-table__column-filter-trigger {
    display: inline-block;
  }
}
/* 列表行hover变色 */
.el-table__body tr:hover>td {
  background-color: rgba(0,0,0,0) !important;
}
.card {
  .el-tabs {
    position: absolute;
  }
}
@media screen and (max-width: 1440px) {
  .el-table{
    font-size: 12px !important;
    th{ // 表头
      padding: 0 0;
    }
    td{
      .el-step__title{
        line-height: 22px;
        font-size: 10px !important;
      }
      .el-step__icon.is-text{
        transform: scale(0.8);
      }
    }
  }
}
@media screen and (min-width: 1920px) {
  .el-table{
    font-size: 12px !important;
  }
}
.el-table--border .el-table__cell {
  border-right: 1px solid #ccc;
}
.el-table--border th.el-table__cell, .el-table__fixed-right-patch {
  border-bottom: 1px solid #ccc;
}
.el-table {
  border: 1px solid #ccc;
  .el-step__title{
    line-height: 24px;
  }
  .el-input .el-input__inner {
    height: 30px;
    line-height: 30px;
  }
  .el-input--mini .el-input__icon, .el-input--mini  iconfont {
    line-height: 23px;
  }
  .el-table__cell {
    padding: 3px 0;
  }
  th {
    padding: 5px 0;
    border-color: #ccc;
    user-select: initial; /* 表头可复制 */
    .cell {
      // white-space: nowrap;
    }
  }

  th.gutter {
    display: table-cell !important
  }

  td.el-table__cell, th.el-table__cell.is-leaf {
    border-bottom: 1px solid #ccc;
  }
  th:last-child {
    border-right: none;
  }
  th>.cell {
    display: inline-block;
    //white-space: nowrap;
    width: auto;
    //overflow: auto;
  }
  td {
    border-color: #ccc;
  }
  td:last-child {
    //border-right: none;
  }
  /* 解决表格固定列后滚动条不能动问题 */
  .el-table__fixed {
    height: auto !important;
    bottom: 16px;
  }
 .el-table__fixed-right-patch{
    top: 0;
  }
}
.el-table .cell, .el-table--border .el-table__cell:first-child .cell,
.el-table th.el-table__cell>.cell {
  padding: 0;
}
.el-input.is-disabled .el-input__inner{
  color: black;
}
.el-table .warning-row{
  background: #ececec;
}
.el-table__expanded-cell[class*=cell]{
  padding: 10px;
}
.el-table th.gutter {
  display: table-cell !important
}
.el-table th>.cell {
  padding: 0;
  //overflow: hidden;
}
.el-table .caret-wrapper {
  width: 24px;
}
.el-table .cell {
  line-height: 23px;
  padding: 0 2px;
}

.el-table .cell,.el-table--border td:first-child .cell, .el-table--border th:first-child .cell {
  padding-left: 0;
}
.el-table__column-filter-trigger {
  line-height: 20px;
}
/*点击行变色*/
//.el-table__body tr.current-row>td {
//  background-color: #fde7c5 !important;
//}

/* 复制 */
.tabModule {
  position: relative;
  .menuDiv {
    display: none;
    position: absolute;

    .menuUl {
      height: auto;
      width: auto;
      font-size: 14px;
      text-align: center;
      border-radius: 3px;
      background-color: #FFF;
      color: #333;
      border: 1px solid #aaa;
      list-style: none;
      padding: 0;
      li {
        width: 100px;
        padding: 5px 10px;
        cursor: pointer;
        border-bottom: 1px solid rgba(255, 255, 255, 0.47);
      }
      li:hover {
        background-color: #eee;
      }
    }
  }
}
</style>
